/**
 * 
 */
package denaris.core;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import denaris.factory.ImageFactory;
import denaris.midlet.DenarisGameCanvas;
import denaris.midlet.GameScreen;
import denaris.midlet.DenarisGameCanvas.DisplayProperties;

/**
 * @author stkl23
 *
 */
public class Scorebar {
	private static Image scorebar = ImageFactory.getImage("/denaris/resource/image/scorebar.png");
	
	private static Scorebar instance;

	private int scoreBottom = 15;
	
	public Scorebar() {
	}
	
	public static Scorebar getInstance() {
		if (instance == null) {
			instance = new Scorebar();
		}
		
		return instance;
	}
	
	private void drawNumber(Graphics buffer, int number, int decimals, int x, int y) {
		int n = 1;
		for (int i=1; i<decimals;i++,n*=10);
		
		for (int i=0; i<decimals;i++) {
			int val = number / n;
			buffer.drawRegion(scorebar, val * 10, 0, 10, 15, 0, x, y, Graphics.LEFT|Graphics.TOP);
			if ((val * n) <= number) {
				number -= val * n;
			}
			n /= 10;
			x += 10;
		}
	}

	public void drawScore(Graphics buffer, int score) {
		DenarisGameCanvas.getInstance().saveCurrentClipping();
		buffer.setClip(0, 0, DisplayProperties.DISPLAY_WIDTH, DisplayProperties.GAME_TOP);
		// draw score
		drawNumber(buffer, score, 7, 0, scoreBottom - 15);
		DenarisGameCanvas.getInstance().restoreClipping();
	}
	
	public void drawArea(Graphics buffer, int area) {
		DenarisGameCanvas.getInstance().saveCurrentClipping();
		buffer.setClip(0, 0, DisplayProperties.DISPLAY_WIDTH, DisplayProperties.GAME_TOP);
		buffer.drawRegion(scorebar, 60, 15, 40, 15, 0, DisplayProperties.DISPLAY_WIDTH - 22, scoreBottom, Graphics.RIGHT|Graphics.BOTTOM);
		drawNumber(buffer, area, 2 , DisplayProperties.DISPLAY_WIDTH - 20, scoreBottom - 15);
		DenarisGameCanvas.getInstance().restoreClipping();
	}
	
	public void doFullRepaint(Graphics buffer) {
		scoreBottom = DisplayProperties.GAME_TOP - 2;
		GameScreen gameScreen = GameScreen.getInstance();
		drawScore(buffer, gameScreen.getPlayer().getScore());
		drawArea(buffer, gameScreen.getCurrentArea());
		// paint the separator line
		buffer.setColor(0x8080F0);
		buffer.drawLine(0, DisplayProperties.GAME_TOP - 1, DisplayProperties.DISPLAY_WIDTH, DisplayProperties.GAME_TOP - 1);
	}

	public int getHeight() {
		return 18;
	}
}